package com.cloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: my
 * @BelongsPackage: com.cloud.service
 * @Author: ji ge
 * @CreateTime: 2024-02-02  13:43
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class PaymentService {

    public String hystrixOk(Integer id) {
        return "线程池："+Thread.currentThread().getName() + "paymentInfoOk,id: " +id +"\t" +"O(∩_∩)O哈哈~";
    }

    @HystrixCommand(fallbackMethod = "paymentInfoTimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String hystrixTimeOut(Integer id) {
        int second =3;
        long start =System.currentTimeMillis();
        try{
            TimeUnit.SECONDS.sleep(second);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        return "线程池： "+ Thread.currentThread().getName() + " paymentInfoTimeOut,id: "+id+"\t"+"O(∩_∩)O哈哈~"+(end-start);
    }
    public String paymentInfoTimeOutHandler(Integer id){
        return "线程池: "+Thread.currentThread().getName()+" paymentInfoTimeOutHandler8001 系统繁忙或者运行报错，稍后 id="+id;
    }

    @HystrixCommand(fallbackMethod = "paymentCircuitBeakerFallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enable",value = "true"),
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")
    })
    public String circuitBreaker(Integer id) {
        if (id<0){
            throw new RuntimeException("id 不能负数");
        }

        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t 调用成功 流水："+serialNumber;
    }

    public String paymentCircuitBreakerFallback(Integer id){
        return Thread.currentThread().getName()+"\t"+"id 不能负数 "+id;
    }
}
